using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class PatientController : ControllerBase
    {
        private readonly IPatientInfoService _patientInfoService;
        private readonly IHisPatientBalanceService _hisPatientBalanceService;
        private readonly ILogger<PatientController> _logger;

        public PatientController(IPatientInfoService patientInfoService, IHisPatientBalanceService hisPatientBalanceService, ILogger<PatientController> logger)
        {
            _patientInfoService = patientInfoService;
            _hisPatientBalanceService = hisPatientBalanceService;
            _logger = logger;
        }

        /// <summary>
        /// 根据患者ID查询患者基本信息和卡内余额
        /// </summary>
        /// <param name="request">包含患者ID的请求</param>
        /// <returns>患者基本信息和余额</returns>
        [HttpPost("get-patient-info")]
        public async Task<ActionResult<PatientInfoResponse>> GetPatientInfo([FromBody] GetPatientInfoRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.PatientId))
                {
                    return BadRequest(new { message = "患者ID不能为空" });
                }

                var patientInfo = await _patientInfoService.GetPatientInfoByIdAsync(request.PatientId);
                
                if (patientInfo == null)
                {
                    return NotFound(new { message = "未找到患者信息" });
                }

                return Ok(patientInfo);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询患者信息失败: {request.PatientId}");
                return StatusCode(500, new { message = "查询患者信息失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 根据患者ID从HIS系统获取qrCode
        /// </summary>
        /// <param name="request">包含患者ID的请求</param>
        /// <returns>患者qrCode</returns>
        [HttpPost("get-qrcode")]
        public async Task<ActionResult<GetQrCodeResponse>> GetQrCode([FromBody] GetQrCodeRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.PatientId))
                {
                    return BadRequest(new { message = "患者ID不能为空" });
                }

                var qrCode = await _hisPatientBalanceService.GetPatientQrCodeAsync(request.PatientId);
                
                return Ok(new GetQrCodeResponse
                {
                    PatientId = request.PatientId,
                    QrCode = qrCode
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询患者qrCode失败: {request.PatientId}");
                return StatusCode(500, new { message = "查询患者qrCode失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 根据患者ID和HIS余额查询退费流水号
        /// </summary>
        /// <param name="request">包含患者ID和HIS余额的请求</param>
        /// <returns>退费流水号</returns>
        [HttpPost("get-refund-balance-sn")]
        public async Task<ActionResult<GetRefundBalanceSnResponse>> GetRefundBalanceSn([FromBody] GetRefundBalanceSnRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.PatientId))
                {
                    return BadRequest(new { message = "患者ID不能为空" });
                }

                var refundBalanceSn = await _hisPatientBalanceService.GetRefundBalanceSnAsync(request.PatientId, request.RefundBalance);
                
                return Ok(new GetRefundBalanceSnResponse
                {
                    PatientId = request.PatientId,
                    HisBalance = request.RefundBalance,
                    RefundBalanceSn = refundBalanceSn
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询患者退费流水号失败: {request.PatientId}, HIS余额: {request.RefundBalance}");
                return StatusCode(500, new { message = "查询患者退费流水号失败", error = ex.Message });
            }
        }

        /// <summary>
        /// 查询HIS退费数据
        /// </summary>
        /// <param name="request">包含患者ID、金额和天数的请求</param>
        /// <returns>HIS退费数据列表</returns>
        [HttpPost("get-his-refund-data")]
        public async Task<ActionResult<GetHisRefundDataResponse>> GetHisRefundData([FromBody] GetHisRefundDataRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.PatientId))
                {
                    return BadRequest(new { message = "患者ID不能为空" });
                }

                var refundDataList = await _hisPatientBalanceService.GetHisRefundDataAsync(request.PatientId, request.Amount, request.Days);
                
                return Ok(new GetHisRefundDataResponse
                {
                    PatientId = request.PatientId,
                    Amount = request.Amount,
                    Days = request.Days,
                    RefundDataList = refundDataList
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"查询HIS退费数据失败: {request.PatientId}, 金额: {request.Amount}, 天数: {request.Days}");
                return StatusCode(500, new { message = "查询HIS退费数据失败", error = ex.Message });
            }
        }
    }

    // 请求模型
    public class GetQrCodeRequest
    {
        public string PatientId { get; set; } = string.Empty;
    }

    // 响应模型
    public class GetQrCodeResponse
    {
        public string PatientId { get; set; } = string.Empty;
        public string? QrCode { get; set; }
    }

    // 查询退费流水号请求模型
    public class GetRefundBalanceSnRequest
    {
        public string PatientId { get; set; } = string.Empty;
        public decimal RefundBalance { get; set; }
    }

    // 查询退费流水号响应模型
    public class GetRefundBalanceSnResponse
    {
        public string PatientId { get; set; } = string.Empty;
        public decimal HisBalance { get; set; }
        public string? RefundBalanceSn { get; set; }
    }

    // 查询HIS退费数据请求模型
    public class GetHisRefundDataRequest
    {
        public string PatientId { get; set; } = string.Empty;
        public decimal Amount { get; set; }
        public int Days { get; set; }
    }

    // 查询HIS退费数据响应模型
    public class GetHisRefundDataResponse
    {
        public string PatientId { get; set; } = string.Empty;
        public decimal Amount { get; set; }
        public int Days { get; set; }
        public List<Models.HisRefundData> RefundDataList { get; set; } = new List<Models.HisRefundData>();
    }
}